//
//  CameraViewController.m
//  ShoppingExperience
//
//  Created by LiYinDi on 15/10/16.
//  Copyright (c) 2015年 RuiBen. All rights reserved.
//

#import "CameraViewController.h"
#import "CaptureViewController.h"
#import "PassImageDelegate.h"
#import "UpYun.h"
@interface CameraViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,PassImageDelegate>
{
   }

@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    // Do any additional setup after loading the view from its nib.
}
#pragma 拍照选择照片协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
   /// isLoad=YES;
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    // NSData *data;
    
    if ([mediaType isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出，很原始，哈哈
        UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        // NSLog(@"originImage.",originImage.size);
        //图片压缩，因为原图都是很大的，不必要传原图
        // UIImage *scaleImage = [self scaleImage:originImage toScale:1.0];
        //  UIImage *sampleImg=[self imageCompress:originImage];
        
        //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
        //       if (UIImagePNGRepresentation(scaleImage) == nil) {
        //将图片转换为JPG格式的二进制数据
        //   data = UIImageJPEGRepresentation(scaleImage, 1.0);
        //        }
        //        else {
        ////          //  将图片转换为PNG格式的二进制数据
        //           data = UIImagePNGRepresentation(scaleImage);
        //       }
        
        
        
        //将二进制数据生成UIImage
        // UIImage *image = [UIImage imageWithData:data];
        
        // NSData *imageData = UIImageJPEGRepresentation(image,0.01);
        //NSLog(@"imageData===%@",imageData);
        // UIImage *newImage = [UIImage imageWithData:imageData];
        
        //将图片传递给截取界面进行截取并设置回调方法（协议）
        CaptureViewController *captureView = [[CaptureViewController alloc] init];
        captureView.delegate = self;
        captureView.image = originImage;
        //隐藏UIImagePickerController本身的导航栏
        picker.navigationBar.hidden = NO;
        [picker pushViewController:captureView animated:YES];
        
    }
}

#pragma mark - 图片回传协议方法
-(void)passImage:(UIImage *)image
{
    UIImage *upImage=[self imageCompress:image];
    if ([self.delegate respondsToSelector:@selector(returnImg:)]) {
        [self.delegate returnImg:upImage];
    }
   // UIImage *sampleImg=image;
    
}


#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

-(IBAction)albumOrCameraBtnClick:(UIButton *)sender
{
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    switch (sender.tag) {
        case 20000://Take picture
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
            }else{
                NSLog(@"模拟器无法打开相机");
            }
            [self presentViewController:picker animated:YES completion:nil];
            break;
            
        case 20001://From album
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
            break;
            
        default:
            
            break;
    }
    
    if (self.view!=nil) {
        
        [self removeFromParentViewController];
        [self.view removeFromSuperview];
        
    }

    
}

-(IBAction)cancelBtnClick:(id)sender
{
    if (self.view!=nil) {
        
        [self removeFromParentViewController];
        [self.view removeFromSuperview];
        
    }
    
    
}

-(NSString * )getSaveKey {
    NSDate *d =[NSDate date];
    int value = arc4random() % 1000;
    return [NSString stringWithFormat:@"/%d/%d/%d.jpg",[self getYear:d],[self getMonth:d],value];
}

- (int)getYear:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    return year;
}

- (int)getMonth:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int month = [comps month];
    return month;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
    [self dismissViewControllerAnimated:NO completion:^{
        
         }];
    
}
-(UIImage *)imageCompress:(UIImage *)image
{
    UIImage *comImage=image;
    NSData * sendImageData = UIImageJPEGRepresentation(comImage, 1.0);
    NSUInteger sizeOrigin = [sendImageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB >100) {
        float a = 100.0000;
        float b = (float)sizeOriginKB;
        float q = sqrtf(a / b);
        
        CGSize sizeImage = [comImage size];
        CGFloat widthSmall = sizeImage.width * q;
        CGFloat heighSmall = sizeImage.height * q;
        CGSize sizeImageSmall = CGSizeMake(widthSmall, heighSmall);
        
        UIGraphicsBeginImageContext(sizeImageSmall);
        CGRect smallImageRect = CGRectMake(0, 0, sizeImageSmall.width, sizeImageSmall.height);
        [image drawInRect:smallImageRect];
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        NSData *dataImage = UIImageJPEGRepresentation(smallImage, 1.0);
        sendImageData = dataImage;
        
        comImage= smallImage;
        // [_imageview1.image retain];
    }
    return comImage;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
